/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import Utility.VarcharUpdater;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import vo.rb_employee;
import vo.rb_purchase;

/**
 *
 * @author Shuhail
 */
public class rb_employees_persist {
    
    Session sess=null;
    Transaction tx = null;
    
    public rb_employees_persist() {
        
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        sess = sf.openSession();
        tx = sess.beginTransaction();
    }
    
    public static rb_employees_persist getInstance() {
        
        return new rb_employees_persist();
    }
   
    public List<rb_employee> getForPopulatingEmployeeTable() {
        
        tx.begin();
        Query query = sess.getNamedQuery("getAllEmployeeDetails");
        List list  = query.list();
        return list;
    }
    
    public boolean insertEmployee(rb_employee emp) {
        
        tx.begin();
        emp.setEmployee_id(VarcharUpdater.getInstance().getValue(this.getLastPK()));
        sess.save(emp);
        tx.commit();
        return true;
    }
    public List<rb_employee> getAllEmployees() {
        
        tx.begin();
        Query query = sess.getNamedQuery("getAllEmployeeDetails");
        List results = query.list();
        return results;
        
    }
    
    public String getLastPK() {
        List<rb_employee> emp = new ArrayList<rb_employee>();
        emp = this.getAllEmployees();
        Iterator it = emp.iterator();
        List<String> list = new ArrayList<String>();
        while(it.hasNext()) {
            rb_employee e = (rb_employee)it.next();
            list.add(e.getEmployee_id());
        }
        String last_pk = VarcharUpdater.getInstance().getTheLastPK(list);
        System.out.println(last_pk);
        return last_pk;
    }
    
    
    public static void main(String[] args) {
        /*
        rb_employees_persist emp = new rb_employees_persist();
        List list = emp.getAllEmployees();
        System.out.println("here");
        Iterator it = list.iterator();
        while(it.hasNext()) {
            System.out.println(((rb_employee)it.next()).getEmployee_name());
        }
        */
        
        rb_employee emp = new rb_employee();
        emp.setEmployee_name("Test");
        emp.setEmployee_type("AdminTest");
        emp.setEmployee_contact_no("123456");
        emp.setEmployee_address("asasasasTest");
        new rb_employees_persist().insertEmployee(emp);
    }
    
}
